<template>
  <div class="upload-file">
    <el-upload
        multiple
        :http-request="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :show-file-list="listType != 'text'"
        class="upload-file-uploader"
        ref="fileUpload"
        :list-type="listType"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :class="{ disabled: !(fileList.length < limit) }"
    >
      <!-- 上传按钮 -->
      <el-icon v-if="listType != 'text'"><Plus /></el-icon>
      <el-button v-if="listType == 'text'" type="primary" :loading="btn_loading">选取文件</el-button>
    </el-upload>
    <div v-if="btn_loading">
      <b style="color: #f56c6c">图片上传中...</b>
    </div>

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      <template v-if="fileSize || fileType">请上传</template>
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      <template v-if="fileSize || fileType">的文件。</template>
      <template v-if="imgSize">图片建议尺寸：<b style="color: #f56c6c">{{ imgSize }}</b> </template>
    </div>
    <!-- 文件列表 -->
    <template v-if="listType == 'text'">
      <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
        <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
          <el-link :href="`${file.url}`" :underline="false" target="_blank">
            <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
          </el-link>
          <div class="ele-upload-list__item-content-action">
            <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
          </div>
        </li>
      </transition-group>
    </template>

    <el-dialog v-model="dialogVisible">
      <div class="dialog-img">
        <img :src="dialogImageUrl" alt="Preview Image" />
      </div>

    </el-dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref, reactive, computed, onMounted, watch, toRefs, onBeforeUnmount} from "vue"
import {Plus} from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const btn_loading = ref(false)
const number = ref(0);
const uploadList = ref([]);
const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 9,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    // default: () => ["apk", "ipa"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  listType:{
    type:String,
    default:'text'
  },
  modelValueType:{
    type:String,
    default:'Array'
  },
  imgSize:{
    type:String,
    default:''
  }
});
// 唯一uuid
const getFileNameUUID = () => {
  function rx() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return `${+new Date()}${rx()}${rx()}`
}

const fileList = ref([]);
const showTip = computed(
    () => props.isShowTip && (props.fileType || props.fileSize || props.imgSize)
);

watch(() => props.modelValue, val => {
  if (val) {
    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : typeof val === "string" ? props.modelValue.split(','):[val];
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        item = { name: item, url: proxy.imgUrl+item};
      }else{
        item = {
          name: item,
          url: proxy.imgUrl + item.imagePath,
          imagePath: item.imagePath,
          status: item.status,
          viewSort: item.viewSort
        };
      }
      item.uid = item.uid || new Date().getTime() + temp++;
      return item;
    });
  } else {
    fileList.value = [];
    return [];
  }
},{ deep: true, immediate: true });

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  console.log('handleBeforeUpload');
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$message({
        message: `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`,
        type: "error"
      })
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$message({
        message: `上传文件大小不能超过 ${props.fileSize} MB!`,
        type: "error"
      })
      // console.log('上传文件大小不能超过');
      return false;
    }
  }
  btn_loading.value = true;
  // proxy.$modal.loading("正在上传文件，请稍候...");
  console.log('正在上传文件');
  number.value++;
  return true;
}

// 文件个数超出
function handleExceed() {
  proxy.$message({
    message:`上传文件数量不能超过 ${props.limit} 个!`,
    type: "error"
  })
}

// 上传失败
function handleUploadError(err) {
  proxy.$message({
    message:`上传文件失败`,
    type: "error"
  })
}

// 上传
// 上传
function handleUploadSuccess(d) {
  let data = new FormData()
  data.append("file", d.file)
  proxy.$axios.post("resources/public", data).then((res) => {
    if (res.data.code == 200) {
      let img = res.data.data;
      let viewSort = uploadList.value.length;
      uploadList.value.push({ name: img.name, url: proxy.imgUrl + img.url,imagePath:img.url,status:0,viewSort:viewSort });
      uploadedSuccessfully();
    } else {
      number.value--;
      // proxy.$modal.closeLoading();
      btn_loading.value = false;
      proxy.$message({
        message:res.msg,
        type: "error"
      })
      proxy.$refs.fileUpload.handleRemove(d.file);
      uploadedSuccessfully();
    }
  }).catch(err => {
    uploadedSuccessfully();
  })

  // proxy.$ossUpload.put(res.file).then(res=>{
  //   // console.log(res)
  //   // res.res.statusCode
  //   if(res.res.statusCode){
  //     uploadList.value.push({ name: res.name, url: proxy.imgUrl + res.name });
  //     uploadedSuccessfully();
  //   }else{
  //     number.value--;
  //     // proxy.$modal.closeLoading();
  //     btn_loading.value = false;
  //     proxy.$message({
  //       message:res.msg,
  //       type: "error"
  //     })
  //     proxy.$refs.fileUpload.handleRemove(file);
  //     uploadedSuccessfully();
  //   }
  // })
}

// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1);
  emit("update:modelValue", getValue(fileList.value));
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit("update:modelValue", getValue(fileList.value));
    // proxy.$modal.closeLoading();
    btn_loading.value = false;
  }
}

// 获取文件名称
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return "";
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].imagePath) {
      // let url = list[i].url.replace(proxy.imgUrl,'');
      strs += list[i].imagePath + separator;
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : '';
}
function getValue(list){
  if(props.modelValueType == 'Array'){
    // let arr = list.map(item => item.url.replace(proxy.imgUrl,''))
    let arr = list.map(item => {
      return {
        "imagePath": item.imagePath,
        "status": item.status,
        "viewSort": item.viewSort
      }
    })
    return arr
  }
  if(props.modelValueType == 'String'){
    return listToString(list)
  }

  if(props.modelValueType == 'Object'){
    let arr = list.map(item => {
      return {
        "imagePath": item.imagePath,
        "status": item.status,
        "viewSort": item.viewSort
      }
    })
    return arr[0]
  }
}


const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  // console.log('handleRemove');
  let index = fileList.value.findIndex(f=>f.uid == uploadFile.uid)
  if(index != -1){
    fileList.value.splice(index, 1);
  }
  // fileList.value = fileList.value.filter(f => f.uid == uploadFile.uid);
  // console.log(fileList.value);
  emit("update:modelValue", getValue(fileList.value));
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

</script>

<style scoped lang="less">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  padding-left: 10px;
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

:deep.disabled .el-upload--picture-card {
  display: none !important;
}
.dialog-img{
  img {
    width: 100%;
    height: auto;
    max-width: 100%;
    object-fit: cover;
  }
}

</style>